from actions.action import Action
from activity import Activity
from util import select_element_for_dict, remove_clicked_item


class TriggerAction(Action):

    def check(self, activity: Activity, config, driver):
        if "trigger_dict" not in config:
            return False
        # 获取触发器列表
        trigger_dict = config["trigger_dict"]

        if not hasattr(activity, "trigger_executed"):
            # 新增已触发的触发器列表,存放触发器tag
            activity.trigger_executed = {}

        def temp(v):
            return v.get("trigger", {}).get("time", 1)

        # 剔除已经触发过的触发器
        remove_clicked_item(activity.trigger_executed, trigger_dict, temp)

        # 从当前界面，筛选满足任意触发器的第一个元素，保存元素跳转执行
        for key, value in trigger_dict.items():
            targets = select_element_for_dict(activity.elements, [value["target"]])
            if len(targets) > 0:
                activity.triggering = {
                    "target": targets.values().__iter__().__next__(),
                    "trigger": value["trigger"],
                    "key": key
                }
                return True

        return False

    def run(self, activity: Activity, config, driver):
        if not hasattr(activity, "triggering"):
            return

        triggering = activity.triggering  # 将要执行的触发器
        trigger = triggering["trigger"]  # 触发器
        target = triggering["target"]  # 触发对象
        action = trigger["action"]  # 触发器触发行为tag
        key = triggering["key"]  # 触发器标识

        # 将触发器，添加到已触发列表，并且+1
        activity.trigger_executed[key] = activity.trigger_executed.get(key, 0) + 1

        if action == "send_key" and "text" in trigger:
            driver.send_key(target, trigger["text"])
            activity.element = target
            activity.action = "click"
            return

        if action == "click":
            activity.click(target)
            return

    def run_next_acton(self):
        return False
